package com.edward.weather.strategy.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.edward.weather.model.WeatherData;
import com.edward.weather.strategy.WeatherApiStrategy;
import com.edward.weather.utils.WeatherUtils;
import com.edward.weather.vo.dto.NowDTO;
import com.edward.weather.vo.request.WeatherRequestVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("qweather")
public class QweatherStrategy implements WeatherApiStrategy {


    @Value("${qweather.api.url}")
    private String apiUrl;

    @Value("${qweather.api.key}")
    private String apiKey;

    @Override
    public WeatherData getWeather(String city) {
        //通过city 获取 location
//        https://api.qweather.com/v7/weather/now

        String nowUrl = apiUrl + "/weather/now?location=%s";
        String url = String.format(nowUrl,city);
        HttpResponse httpResponse = HttpRequest.get(url).header("X-QW-Api-Key",apiKey).execute();
//        HttpResponse httpResponse = HttpRequest.get(url).header("Authorization","Bearer "+ WeatherUtils.getWeatherIcon()).execute();
        String responseStr = httpResponse.body();
        return parseWeatherData(responseStr);
    }

    @Override
    public WeatherData dayWeather(WeatherRequestVO weatherRequestVO) {
        String nowUrl = apiUrl + "/weather/%s?location=%s";
        String url = String.format(nowUrl,weatherRequestVO.getDay(), weatherRequestVO.getLocationId());
        HttpResponse httpResponse = HttpRequest.get(url).header("X-QW-Api-Key",apiKey).execute();
        return parseWeatherData(httpResponse.body());
    }

    @Override
    public WeatherData parseWeatherData(String responseStr) {
        JSONObject jsonObject = JSONUtil.parseObj(responseStr);
        WeatherData weatherData = new WeatherData();
        weatherData.setFxLink(jsonObject.getStr("fxLink"));
        NowDTO nowDTO = jsonObject.get("now", NowDTO.class);
        weatherData.setNow(nowDTO);
        return weatherData;
    }
}